import java.io.*;
import java.net.*;

public class ForwarderTest_UDPSender {
    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: java ForwarderTest_Sender <file_path> <target_ip> <target_port>");
            return;
        }

        String filePath = args[0];
        String targetIP = args[1];
        int targetPort = Integer.parseInt(args[2]);

        try
        {
            MulticastSocket socket = new MulticastSocket();
            FileInputStream fis = new FileInputStream(filePath);

            // 加入组播地址
            InetAddress group = InetAddress.getByName(targetIP);
            socket.joinGroup(group);

            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;

            System.out.println("Start sending file: " + filePath);
            while ((bytesRead = fis.read(buffer)) != -1) {
                DatagramPacket packet = new DatagramPacket(buffer, bytesRead, group, targetPort);
                socket.send(packet);
                System.out.print(".");
            }

            // 发送结束标记
            byte[] endSignal = "END".getBytes();
            DatagramPacket endPacket = new DatagramPacket(endSignal, endSignal.length, group, targetPort);
            socket.send(endPacket);

            System.out.println("\nFile sent successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
